import json

from django.db.models import Q
from django.http import HttpResponse
from .models import Student


# Create your views here.

def fn_add(request):
    """数据添加"""
    #  如何将数据保存到数据库   pymysql  crud  封装函数
    # student = Student(name='tom', age=18, score=90, stu_no='20250429001')
    # 保存数据到数据库
    # student.save()

    # 保存数据的方式2  save
    Student.objects.create(name='xiaoming', age=18, score=90, stu_no='20250429001')

    return HttpResponse('<h1>add ok</h1>')


def fn_delete(request):
    """数据删除"""
    Student.objects.filter(id=1).delete()  # 删除id=1的一条记录
    return HttpResponse('<h1>delete ok</h1>')


def fn_update(request):
    """数据修改"""
    # student = Student.objects.filter(id=2).first()
    # student.score = 85
    # student.name = 'Tom'
    # 保存数据
    # student.save()

    # 更新的方式2  auto_now = true  不生效
    Student.objects.filter(id=2).update(name='xiaohei', age=30)

    return HttpResponse('<h1>update ok</h1>')


def fn_list(request):
    """数据列表"""
    """
    all()     QuerySet  [object,object]
    values()  QuerySet  [{},{},{}]
    values('id','name','score')   指定查询的字段
    values_list()    QuerySet  [(),(),()]
    order_by(字段名)  默认 正序    -id   倒序
    """
    students = Student.objects.all().values('id', 'name', 'score').order_by('-id')  # 查询所有数据
    for student in students:
        print(student)
    return HttpResponse('<h1>select list ok</h1>')


def fn_query(request):
    """条件查询"""
    """
    filter(id=2)   where id = 2
    filter(id=2,name='jack')   where id = 2 and name = 'jack'
    
    filter(id__gt=2)    where id > 2
    filter(id__range=[2,10])   between
    
    where id =2  or name = 'tom
    """
    # result = Student.objects.filter(id__gt=2).first()  # 获取结果集中的第一条记录
    # result = Student.objects.filter(id__gte=2)
    # result = Student.objects.filter(id__lte=2)
    # result = Student.objects.filter(id__range=[2,10])
    # result = Student.objects.filter(name__startswith='l')
    # result = Student.objects.filter(name__endswith='m')
    # result = Student.objects.filter(name__contains='m')
    #  or

    q1 = Q(id=2, age=20)
    q2 = Q(name='tom')

    result = Student.objects.filter(q1 | q2)  # where  (id =2 and age =20) or name = tom
    # and
    # result = Student.objects.filter(q1 & q2)
    print(result)
    return HttpResponse('<h1>query ok</h1>')


